package cn.you.GenghisKhan.common.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import java.util.Map;

//@Controller
@Component("SpringContextHolder")
public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext (ApplicationContext applicationContext) {
        SpringContextHolder.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext () {
        checkApplicationContext();
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static Object getBean (String name) {
        try {
            checkApplicationContext();
            return applicationContext.getBean(name);
        } catch (Exception x) {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean (Class clazz) {
        try {
            checkApplicationContext();
            Map beanMaps = applicationContext.getBeansOfType(clazz);
            if (beanMaps != null && !beanMaps.isEmpty()) {
                return (T) beanMaps.values().iterator().next();
            } else {
                return null;
            }
        } catch (Exception x) {
            return null;
        }
    }

    private static void checkApplicationContext () {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入");
        }
    }
}